<!--
  结算管理主页面
  @description 结算单管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('settle.settleOrder.settleNo')" prop="settleNo">
        <el-input
          v-model="queryParams.settleNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.settleOrder.settleNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.settleOrder.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.settleOrder.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.settleOrder.settleCycle')" prop="settleCycle">
        <el-select
          v-model="queryParams.settleCycle"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.settleOrder.settleCycle')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in settleCycleOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('settle.common.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.common.status')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in statusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('settle.settleOrder.settleDate')" prop="settleDate">
        <el-date-picker
          v-model="queryParams.settleDate"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('settle.common.startTime')"
          :end-placeholder="t('settle.common.endTime')"
          value-format="YYYY-MM-DD"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('settle.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('settle.common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleGenerate"
          v-hasPermi="['settle:settle-order:generate']"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          {{ t('settle.settleOrder.generate') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['settle:settle-order:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('settle.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column
        :label="t('settle.settleOrder.settleNo')"
        align="center"
        prop="settleNo"
        width="200"
      />
      <el-table-column
        :label="t('settle.settleOrder.merchantNo')"
        align="center"
        prop="merchantNo"
        width="180"
      />
      <el-table-column
        :label="t('settle.settleOrder.merchantName')"
        align="center"
        prop="merchantName"
        min-width="150"
      />
      <el-table-column
        :label="t('settle.settleOrder.settleCycle')"
        align="center"
        prop="settleCycle"
        width="100"
      >
        <template #default="scope">
          <el-tag :type="getSettleCycleTagType(scope.row.settleCycle)">
            {{ settleCycleOptions[scope.row.settleCycle] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.settleOrder.settleAmount')"
        align="center"
        prop="settleAmount"
        width="120"
      >
        <template #default="scope"> ¥{{ (scope.row.settleAmount / 100).toFixed(2) }} </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.settleOrder.feeAmount')"
        align="center"
        prop="feeAmount"
        width="100"
      >
        <template #default="scope"> ¥{{ (scope.row.feeAmount / 100).toFixed(2) }} </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.settleOrder.actualAmount')"
        align="center"
        prop="actualAmount"
        width="120"
      >
        <template #default="scope"> ¥{{ (scope.row.actualAmount / 100).toFixed(2) }} </template>
      </el-table-column>
      <el-table-column :label="t('settle.common.status')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ statusOptions[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.settleOrder.settleDate')"
        align="center"
        prop="settleDate"
        width="120"
      />
      <el-table-column
        :label="t('settle.common.createTime')"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column
        :label="t('settle.common.operation')"
        align="center"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['settle:settle-order:query']"
          >
            {{ t('settle.common.view') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['settle:settle-order:confirm']"
            v-if="scope.row.status === SettleOrderStatusEnum.PENDING"
          >
            {{ t('settle.settleOrder.confirm') }}
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleReject(scope.row)"
            v-hasPermi="['settle:settle-order:reject']"
            v-if="scope.row.status === SettleOrderStatusEnum.PENDING"
          >
            {{ t('settle.settleOrder.reject') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['settle:settle-order:delete']"
            v-if="scope.row.status === SettleOrderStatusEnum.PENDING"
          >
            {{ t('settle.common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 结算单详情 -->
  <SettleOrderDetail ref="detailRef" />

  <!-- 生成结算单对话框 -->
  <GenerateSettleDialog ref="generateDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import {
  getSettleOrderPageApi,
  cancelSettleApi,
  executeSettleApi,
  exportSettleOrderApi
} from '@/api/settle/settleOrder'
import type { SettleOrderVO, SettleOrderPageReqVO } from '@/api/settle/types'
import { SettleOrderStatusEnum, SettleCycleEnum } from '@/api/settle/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import SettleOrderDetail from './SettleOrderDetail.vue'
import GenerateSettleDialog from './GenerateSettleDialog.vue'

defineOptions({ name: 'SettleSettleOrder' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<SettleOrderVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<SettleOrderPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  settleNo: undefined,
  merchantNo: undefined,
  settleCycle: undefined,
  status: undefined,
  settleDate: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const detailRef = ref()
const generateDialogRef = ref()

// 选项数据
const settleCycleOptions = {
  [SettleCycleEnum.DAILY]: t('settle.settleOrder.settleCycles.daily'),
  [SettleCycleEnum.WEEKLY]: t('settle.settleOrder.settleCycles.weekly'),
  [SettleCycleEnum.MONTHLY]: t('settle.settleOrder.settleCycles.monthly')
}

const statusOptions = {
  [SettleOrderStatusEnum.PENDING]: t('settle.settleOrder.statuses.pending'),
  [SettleOrderStatusEnum.CONFIRMED]: t('settle.settleOrder.statuses.confirmed'),
  [SettleOrderStatusEnum.REJECTED]: t('settle.settleOrder.statuses.rejected'),
  [SettleOrderStatusEnum.SETTLED]: t('settle.settleOrder.statuses.settled')
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSettleOrderPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询结算单列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 查看详情
 */
const openDetail = (row: SettleOrderVO) => {
  detailRef.value.open(row)
}

/**
 * 生成结算单
 */
const handleGenerate = () => {
  generateDialogRef.value.open()
}

/**
 * 确认结算单
 */
const handleConfirm = async (row: SettleOrderVO) => {
  try {
    await ElMessageBox.confirm(
      t('settle.settleOrder.tips.confirmConfirm'),
      t('settle.common.confirmTitle'),
      {
        confirmButtonText: t('settle.common.confirm'),
        cancelButtonText: t('settle.common.cancel'),
        type: 'warning'
      }
    )

    await executeSettleApi(row.id)
    ElMessage.success(t('settle.settleOrder.tips.confirmSuccess'))
    await getList()
  } catch (error) {
    console.error('确认结算单失败:', error)
  }
}

/**
 * 拒绝结算单
 */
const handleReject = async (row: SettleOrderVO) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      t('settle.settleOrder.rejectReason'),
      t('settle.settleOrder.reject'),
      {
        confirmButtonText: t('settle.common.confirm'),
        cancelButtonText: t('settle.common.cancel'),
        inputType: 'textarea',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return t('settle.common.pleaseInput') + t('settle.settleOrder.rejectReason')
          }
          return true
        }
      }
    )

    await cancelSettleApi(row.id)
    ElMessage.success(t('settle.settleOrder.tips.rejectSuccess'))
    await getList()
  } catch (error) {
    console.error('拒绝结算单失败:', error)
  }
}

/**
 * 删除按钮操作
 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await cancelSettleApi(id)
    message.success(t('settle.settleOrder.tips.deleteSuccess'))
    await getList()
  } catch (error) {
    console.error('删除结算单失败:', error)
  }
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportSettleOrderApi(queryParams)
    message.success(t('settle.common.exportSuccess'))
  } catch (error) {
    console.error('导出结算单数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getSettleCycleTagType = (cycle: number) => {
  const cycleMap = {
    [SettleCycleEnum.DAILY]: 'primary',
    [SettleCycleEnum.WEEKLY]: 'success',
    [SettleCycleEnum.MONTHLY]: 'warning'
  }
  return cycleMap[cycle] || ''
}

const getStatusTagType = (status: number) => {
  const statusMap = {
    [SettleOrderStatusEnum.PENDING]: 'warning',
    [SettleOrderStatusEnum.CONFIRMED]: 'primary',
    [SettleOrderStatusEnum.REJECTED]: 'danger',
    [SettleOrderStatusEnum.SETTLED]: 'success'
  }
  return statusMap[status] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>
